package se.recept.kollen.module.bean;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.RedirectResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.UrlBinding;
import net.sourceforge.stripes.validation.LocalizableError;
import net.sourceforge.stripes.validation.Validate;
import se.recept.kollen.model.User;

/**
 *
 * @author jocke
 */
@UrlBinding("/action/login")
public class LoginActionBean extends DefaultActionBean {

    private static final Logger LOG = Logger.getLogger(LoginActionBean.class.getName());

    @Validate(required = true, trim = true)
    private String username;

    @Validate(required = true, trim = true)
    private String password;

    @Inject
    private EntityManager em;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @DefaultHandler
    public Resolution login() {
        try {
            User user = em.createNamedQuery(User.FIND_BY_NAME, User.class).setParameter("name", username).getSingleResult();
            if (user.getPassword().equals(password)) {
                setCustomer(user.getCustomer());
                return new RedirectResolution(Pages.HOME);
            } else {
                return rejectLogin();
            }
        } catch (NoResultException e) {
            return rejectLogin();
        }
    }

    private Resolution rejectLogin() {
        LOG.log(Level.WARNING, "Rejecting user {0} invalid login", username);
        getContext().getValidationErrors().addGlobalError(new LocalizableError("common.login.failed.text"));
        LOG.info(getContext().getSourcePage());
        return new ForwardResolution(Pages.INDEX);
    }
}
